//
//  LXMapDetailViewController.m
//  LXLocationRelated
//
//  Created by Livespro on 2017/10/26.
//  Copyright © 2017年 Livesxu. All rights reserved.
//

#import "LXMapDetailViewController.h"

#import <MapKit/MapKit.h>
#import "MKPointAnnotation+LXImage.h"

#import "LXDistanceDescription.h"
#import "LXHandleDatas.h"

@interface LXMapDetailViewController ()<MKMapViewDelegate>

@property (nonatomic, strong) MKMapView *mapView;

@end

@implementation LXMapDetailViewController

- (void)dealloc {
    self.mapView.delegate = nil;
    self.mapView = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view addSubview:self.mapView];
    if (_isLocalDatas) {
        
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"timestamp >= %@ AND timestamp <= %@",
                                  _startDate,_endDate];
        RLMResults *distances = [LXDistanceDescription objectsWithPredicate:predicate];
        
        NSMutableArray *gpsPionts = [NSMutableArray array];
        for (LXDistanceDescription *distance in distances) {
            
            MapLocationModel *mapModel = [[MapLocationModel alloc]init];
            mapModel.longitude = distance.longitude;
            mapModel.latitude = distance.latitude;
            
            [gpsPionts addObject:mapModel];
        }
        
        [self drawLocations:gpsPionts];
    } else {
        
    }
}

- (MKMapView *)mapView{
    
    if (!_mapView) {
        
        _mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width)];
        //设置地图的显示风格
        _mapView.mapType = MKMapTypeStandard;
        
        //设置显示用户显示位置
        _mapView.showsUserLocation = NO;
        //为MKMapView设置delegate
        _mapView.delegate = self;
        
        // 是否显示指南针
        _mapView.showsCompass = YES;
        // 是否显示比例尺
        _mapView.showsScale = YES;
//        // 是否显示交通
//        _mapView.showsTraffic = YES;
//        // 是否显示建筑物
//        _mapView.showsBuildings = YES;
    }
    return _mapView;
}

#pragma mark - Draw
//画轨迹
- (void)drawLocations:(NSArray<__kindof MapLocationModel *> *)locations {
    //纬度
    CLLocationDegrees minLatitude = 90;
    CLLocationDegrees maxLatitude = -90;
    
    //经度
    CLLocationDegrees minLongitude = 180;
    CLLocationDegrees maxLongitude = -180;
    
    //绘制新的
    NSArray *driveGPSArray = locations;
    if (driveGPSArray.count == 0) {
        return;
    }
    
    //点
    CLLocationCoordinate2D *coords = (CLLocationCoordinate2D *)malloc(sizeof(CLLocationCoordinate2D)*driveGPSArray.count);
    
    for (NSUInteger i = 0; i < driveGPSArray.count; ++i) {
        LXDistanceDescription *gpsInfo = [driveGPSArray objectAtIndex:i];
        
        double lat = gpsInfo.latitude;
        double lng = gpsInfo.longitude;
        
        coords[i].latitude = lat;
        coords[i].longitude = lng;
        
        minLatitude = MIN(minLatitude, lat);
        maxLatitude = MAX(maxLatitude, lat);
        
        minLongitude = MIN(minLongitude, lng);
        maxLongitude = MAX(maxLongitude, lng);
    }
    
    MKCoordinateRegion coordinateRegion;
    coordinateRegion.center.latitude = (minLatitude + maxLatitude)/2;
    coordinateRegion.center.longitude = (minLongitude + maxLongitude)/2;
    
    //阀值限定，否则会导致崩溃
    coordinateRegion.center.longitude = MIN(MAX(coordinateRegion.center.longitude, -180), 180);
    coordinateRegion.center.latitude = MIN(MAX(coordinateRegion.center.latitude, -90), 90);
    
    coordinateRegion.span.latitudeDelta = (maxLatitude - minLatitude);
    coordinateRegion.span.latitudeDelta += coordinateRegion.span.latitudeDelta/10/*留有一定边距*/;
    
    coordinateRegion.span.longitudeDelta = (maxLongitude - minLongitude);
    coordinateRegion.span.longitudeDelta += coordinateRegion.span.longitudeDelta/10;
    
    @try {
        coordinateRegion = [self.mapView regionThatFits:coordinateRegion];
        [self.mapView setRegion:coordinateRegion animated:NO];
    } @catch (NSException *exception) {
        NSLog(@"%@", exception);
    } @finally {
    }
    
    
    MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coords count:driveGPSArray.count];
    [self.mapView addOverlay:polyline level:MKOverlayLevelAboveLabels];
    
    //起点
    MKPointAnnotation *startAnnotation = [[MKPointAnnotation alloc] init];
    CLLocationCoordinate2D firstCoordinate = coords[0];
    [startAnnotation setCoordinate:firstCoordinate];
    startAnnotation.imageName = @"drive_start.png";
    [self.mapView addAnnotation:startAnnotation];
    
    //终点
    MKPointAnnotation *endAnnotation = [[MKPointAnnotation alloc] init];
    CLLocationCoordinate2D lastCoordinate = coords[driveGPSArray.count-1];
    [endAnnotation setCoordinate:lastCoordinate];
    endAnnotation.imageName = @"drive_end.png";
    [self.mapView addAnnotation:endAnnotation];
    
    free(coords);
    coords = NULL;
}

#pragma mark - MapView Delegate
static NSString *PointReuseIdentifier = @"pointReuseIdentifier";

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    MKAnnotationView *annotationView = (MKAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:PointReuseIdentifier];
    if (annotationView == nil) {
        annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:PointReuseIdentifier];
    }
    
    annotationView.canShowCallout = NO;
    
    if ([annotation respondsToSelector:@selector(imageName)]) {
        
        if (((MKPointAnnotation *)annotation).imageName) {
            UIImage *startImage = [UIImage imageNamed:((MKPointAnnotation *)annotation).imageName];
            [annotationView setImage:startImage];
        }
    }
    
    [annotationView setAnnotation:annotation];
    
    annotationView.centerOffset = CGPointMake(0, -annotationView.frame.size.height/2);
    
    return annotationView;
}

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
    MKOverlayRenderer *overlayRenderer = [mapView rendererForOverlay:overlay];
    if (!overlayRenderer) {
        if ([overlay isKindOfClass:[MKPolyline class]]) {
            overlayRenderer = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
            ((MKPolylineRenderer *)overlayRenderer).strokeColor = [UIColor colorWithRed:62/255.0 green:159/255.0 blue:232/255.0 alpha:1];
            ((MKPolylineRenderer *)overlayRenderer).lineWidth = 3;
        }
    }
    return overlayRenderer;
}


@end

@implementation MapLocationModel

@end
